<?php

namespace common\models;

use common\cache\DictCache;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\helpers\TransformApi;
use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "{{%coupon}}".
 *
 * @property int $id
 * @property int|null $type 类型
 * @property float|null $recharge_amount 充值金额
 * @property int|null $invit_num 邀请人数
 * @property float|null $discount_amount 优惠金额
 * @property string|null $title 名称
 * @property int|null $campus_id 校区
 * @property int|null $status 状态
 * @property int|null $sort 排序
 * @property string|null $create_time 创建时间
 * @property string|null $update_time 修改时间
 * @property int|null $receive_num 领券人数
 * @property int|null $use_num 使用人数
 */
class Coupon extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%coupon}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['type', 'invit_num', 'campus_id', 'status', 'sort', 'receive_num', 'use_num'], 'integer'],
            [['recharge_amount', 'discount_amount'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['title'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'type' => '类型',
            'recharge_amount' => '充值金额',
            'invit_num' => '邀请人数',
            'discount_amount' => '优惠金额',
            'title' => '名称',
            'campus_id' => '校区',
            'status' => '状态',
            'sort' => '排序',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'receive_num' => '领券人数',
            'use_num' => '使用人数',
        ];
    }

    public function verific($post)
    {
        if (empty($post['title'])){
            if ($post['type']==1){
                $post['title'] = '充值优惠券';
            }
            if ($post['type']==2){
                $post['title'] = '分享拉新优惠券';
            }
        }
        if ($post['type']==1){
            if (empty($post['recharge_amount'])){
                return commonApi::message('请输入充值金额',false);
            }
            $post['invit_num'] = 0;
        }
        if ($post['type']==2){
            if (empty($post['invit_num'])){
                return commonApi::message('请输入邀请人数',false);
            }
            $post['recharge_amount'] = 0;
        }
        return commonApi::message('ok',true,$post);
    }

    /**
     * 获取卡券列表
     * @param $userid
     * @param $page
     * @return array
     */
    public function getList($userid,$page)
    {
        $query = self::find()
            ->select(['id','title','discount_amount','type','recharge_amount','invit_num','campus_id'])
            ->where(['status'=>1])
            ->orderBy(['sort'=>SORT_DESC]);
        $data = PageApi::apiPage($query,$page);
        $campus_ids = array_column($data['data'],'campus_id');
        $ids = array_column($data['data'],'id');
        $usecoupon = [];
        $sub_num = 0;
        $recharge_amount = 0;
        if ($userid){
            $usec = UserCoupon::find()->where(['coupon_id'=>$ids,'userid'=>$userid])->select(['coupon_id','use'])->asArray()->all();
            $usecoupon = array_column($usec,'use','coupon_id');
            $sub_num = User::find()->where(['id'=>$userid])->select(['sub_num'])->scalar();
            $sub_num = $sub_num??0;
        }
        $campus = (new Campus())->getCampusName($campus_ids);
        $arr = [];
        $user_coupon_use = DictCache::get('user_coupon_use');
        foreach ($data['data'] as $datum){
            $one = $this->oneData($sub_num,$usecoupon,$user_coupon_use,$recharge_amount,$campus,$datum);
            $one['c_id'] = $datum['id'];
            $arr[] = $one;
        }
        $data['data'] = $arr;
        return commonApi::message('ok',true,$data);
    }

    /**
     * 判断能不能领取
     * @param $sub_num 下级数量
     * @param $usecoupon 已经领取的券
     * @param $user_coupon_use 用户使用
     * @param $recharge_amount 充值金额
     * @param $info 卡券信息
     * @return array
     */
    public function judgedraw($sub_num,$usecoupon,$user_coupon_use,$recharge_amount,$info)
    {
        //0：不满足条件 1：待领取 2：待使用 3：已使用
        $status = 0;
        $status_title = '为满足条件';
        if (isset($usecoupon[$info['id']])){
            $status_title = $user_coupon_use[$usecoupon[$info['id']]]??'';
            $status = $usecoupon[$info['id']]+2;
        }else{
            if ($info['type']==1){
               if ($recharge_amount>=$info['recharge_amount']){
                   $status_title = '待领取';
                   $status = 1;
               }
            }
            if ($info['type']==2){
                if ($sub_num>=$info['invit_num']){
                    $status_title = '待领取';
                    $status = 1;
                }
            }
        }
        return ['status'=>$status,'status_title'=>$status_title];
    }

    /**
     * 领取
     * @param $userid 用户id
     * @param $c_id 优惠券id
     * @return array
     */
    public function receive($userid,$c_id)
    {
        $coupon = self::findOne(['id'=>$c_id,'status'=>1]);
        if (!$coupon){
            return commonApi::message('',false);
        }
        $info = $coupon->toArray();
        $recharge_amount = 0;
        $usec = UserCoupon::find()->where(['coupon_id'=>$c_id,'userid'=>$userid])->select(['coupon_id','use'])->asArray()->all();
        $usecoupon = array_column($usec,'use','coupon_id');
        $sub_num = User::find()->where(['id'=>$userid])->select(['sub_num'])->scalar();
        $user_coupon_use = DictCache::get('user_coupon_use');
        $result = $this->judgedraw($sub_num,$usecoupon,$user_coupon_use,$recharge_amount,$info);
        if ($result['status']!==1){
            return commonApi::message($result['status_title'],false);
        }
        $model = new UserCoupon();
        $model->coupon_id = $coupon->id;
        $model->userid = $userid;
        $model->discount_amount = $userid;
        $model->use = 0;
        $model->status = 1;
        $model->delete = 0;
        $model->coupon_info = json_encode($info);
        $model->campus_id = empty($coupon->campus_id)?0:$coupon->campus_id;
        $coupon->receive_num += 1;
        TransformApi::tx(function ()use ($model,$coupon){
            if ($coupon->save()&&$model->save()){
                return commonApi::message('领取成功');
            }
            throw new Exception('领取失败');
        },$result);
        return $result;
    }

    /**
     * 获取一条数据
     * @param $sub_num 下级数量
     * @param $usecoupon 已经领取的券
     * @param $user_coupon_use 用户使用
     * @param $recharge_amount 充值金额
     * @param $data 卡券信息
     * @return array
     */
    public function oneData($sub_num,$usecoupon,$user_coupon_use,$recharge_amount,$campus,$data)
    {
        $data['desc'] = '';
        if ($data['type']==1){
            $data['desc'] = '充值'.$data['recharge_amount'].'元可领取';
        }
        if ($data['type']==2){
            $data['desc'] = '拉新'.$data['invit_num'].'人可领取';
        }
        $data['astrict'] = '全校通用';
        if ($data['campus_id']){
            $ca = $campus[$data['campus_id']]??'';
            $data['astrict'] = $ca.'使用';
        }
        $judgedraw = $this->judgedraw($sub_num,$usecoupon,$user_coupon_use,$recharge_amount,$data);
        $arr = [
            'c_id' => $data['id'],
            'desc' => $data['desc'],
            'discount_amount' => $data['discount_amount'],
            'astrict' => $data['astrict'],
            'title' => $data['title'],
            'status' => $judgedraw['status'],
            'status_title' => $judgedraw['status_title'],
            'name' => '优惠券',
        ];
        return $arr;
    }
}
